import express from 'express'
import jwt from 'jsonwebtoken'
import cookieParser from 'cookie-parser'

const app = express()
app.use(express.json())
app.use(cookieParser())

// 模拟用户数据
const users = [
  { id: 1, username: 'admin', password: '123456' }
]

// Token密钥
const ACCESS_TOKEN_SECRET = 'your-access-token-secret'
const REFRESH_TOKEN_SECRET = 'your-refresh-token-secret'

// Token过期时间
const ACCESS_TOKEN_EXPIRY = '15m' // 15分钟
const REFRESH_TOKEN_EXPIRY = '7d' // 7天

// 生成Token
const generateTokens = (user) => {
  const accessToken = jwt.sign(
    { id: user.id, username: user.username },
    ACCESS_TOKEN_SECRET,
    { expiresIn: ACCESS_TOKEN_EXPIRY }
  )

  const refreshToken = jwt.sign(
    { id: user.id },
    REFRESH_TOKEN_SECRET,
    { expiresIn: REFRESH_TOKEN_EXPIRY }
  )

  return { accessToken, refreshToken }
}

// 验证Token中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]

  if (!token) {
    return res.status(401).json({ message: '未提供Token' })
  }

  jwt.verify(token, ACCESS_TOKEN_SECRET, (err, user) => {
    if (err) {
      return res.status(401).json({ message: 'Token已过期或无效' })
    }
    req.user = user
    next()
  })
}

// 登录接口
app.post('/login', (req, res) => {
  const { username, password } = req.body
  const user = users.find(u => u.username === username && u.password === password)

  if (!user) {
    return res.status(401).json({ message: '用户名或密码错误' })
  }

  const { accessToken, refreshToken } = generateTokens(user)

  // 设置refreshToken为httpOnly cookie
  res.cookie('refreshToken', refreshToken, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict',
    maxAge: 7 * 24 * 60 * 60 * 1000 // 7天
  })

  res.json({
    accessToken,
    username: user.username
  })
})

// 刷新Token接口
app.post('/refresh', (req, res) => {
  const refreshToken = req.cookies.refreshToken

  if (!refreshToken) {
    return res.status(401).json({ message: '未提供refreshToken' })
  }

  jwt.verify(refreshToken, REFRESH_TOKEN_SECRET, (err, user) => {
    if (err) {
      return res.status(401).json({ message: 'refreshToken已过期或无效' })
    }

    const dbUser = users.find(u => u.id === user.id)
    if (!dbUser) {
      return res.status(401).json({ message: '用户不存在' })
    }

    const { accessToken } = generateTokens(dbUser)
    res.json({ accessToken })
  })
})

// 受保护的接口
app.get('/protected', authenticateToken, (req, res) => {
  res.json({ message: '这是受保护的数据', user: req.user })
})

// 测试Token过期的接口
app.get('/test-expired', authenticateToken, (req, res) => {
  res.json({ message: '访问成功', user: req.user })
})

const PORT = 3000
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`)
})